import pygame, os, sys #@UnresolvedImport
from Nanobot import Nanobot
from Game import GameGrid
from Environment import Goal

'''
    The MasterComputer class both analyzes the input, and assigns each
    bot a task to complete.
'''

def MasterComputer(task):
    grid = GameGrid()
    gridsize = 10
    
    path = sys.path[0]
    file = open(os.path.join(path, "../tasks/",task))
    contents = file.read()
    items = contents.split("\n")
    bots = []
    goals = []
    
    # Reads in the task file, and record the locations of all objects
    for item in items:
        props = item.split(" ")
        if int(props[0]) == 1:
            bots.append(Nanobot(props[1],(int(props[2]),int(props[3])),grid,gridsize))
        elif int(props[0]) == 2:
            goals.append(Goal(props[1],(int(props[2]),int(props[3])),grid,gridsize))
        else:
            print "Error, object type not defined"
            return None
    if len(bots)>len(goals):
        print "Error, more bots than goals"
        return None
    
    # Now the MasterComputer looks at the distances from each bot to each
    # goal, and assigns each bot a goal point. At this point, the system
    # does not look for the optimal solution.
    distancelists = []
    for bot in bots:
        dlist = []
        for goal in goals:
            griddistance = abs(bot.rect.centerx-goal.rect.centerx)+abs(bot.rect.centery-goal.rect.centery)
            dlist.append(griddistance)
        distancelists.append(dlist)
    
    targets = []
    for list in distancelists:
        for target in targets:
            # Prevent a single goal from being assinged to multiple bots.
            list[target]=3*(GameGrid.width+GameGrid.height)
        slist = sorted(list)
        goalsquare = list.index(slist[0]) # gets the smallest distance in the
                                          # current bot's list
        targets.append(goalsquare)
    return [grid,targets]